﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/15 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 天平管理窗体
    /// </summary>
    public partial class FormGagf : HWFrmWithTitle
    {
        byte[] mReadWeightCommand = new byte[] { 0x51, 0x0D, 0x0A };
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormGagf()
        {
            InitializeComponent();
        }
        private void FormGagf_Load(object sender, EventArgs e)
        {
            InitGagfColumns();
            LoadGagfConfig();
            this.labelStart.Select();
        }
        private void LoadGagfConfig()
        {
            this.dataGridViewSerial.Rows.Clear();
            this.dataGridViewTcp.Rows.Clear();
            var otherConfig = BusinessConfig.Instance();
            this.textBoxTimeout.Text = otherConfig.GagfTimeout.ToString();
            this.radioButtonQ.Checked = otherConfig.GagfIsQ;
            this.radioButtonS.Checked = !otherConfig.GagfIsQ;
            this.checkBoxConfirmRead.Checked = otherConfig.GagfWeight2;
            this.checkBoxRezeroACK.Checked = otherConfig.GagfRezeroAck;
            var tcpConfigs = GagfHelper.GetAutoGagfTcpConfig();
            if (tcpConfigs != null && tcpConfigs.Count > 0)
            {
                foreach (var t in tcpConfigs)
                {
                    var index = this.dataGridViewTcp.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewTcp.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["TcpIP"].Value = t.ServerIP;
                    newRow.Cells["TcpPort"].Value = t.ServerPort.ToString();
                    newRow.Cells["Trigger"].Value = t.TriggerAddress;
                    newRow.Cells["TriggerZero"].Value = t.TriggerZeroAddress;
                    newRow.Cells["Done"].Value = t.ResultDoneAddress;
                    newRow.Cells["ZeroDone"].Value = t.ZeroDoneAddress;
                    newRow.Cells["Result"].Value = t.ResultAddress;
                }
            }
            var comConfigs = GagfHelper.GetAutoGagfComConfig();
            if (comConfigs != null && comConfigs.Count > 0)
            {
                foreach (var t in comConfigs)
                {
                    var index = this.dataGridViewSerial.Rows.Add(1);
                    DataGridViewRow newRow = this.dataGridViewSerial.Rows[index];
                    newRow.Cells["Name"].Value = t.Remark;
                    newRow.Cells["PortName"].Value = !string.IsNullOrWhiteSpace(t.PortName) && PortNames.Contains(t.PortName) ? t.PortName : PortNames[0];
                    newRow.Cells["Parity"].Value = t.Parity.ToString();
                    newRow.Cells["DataBit"].Value = t.DataBits.ToString();
                    newRow.Cells["StopBit"].Value = t.StopBits.ToString();
                    newRow.Cells["BaudRate"].Value = t.BaudRate.ToString();
                    newRow.Cells["Trigger"].Value = t.TriggerAddress;
                    newRow.Cells["TriggerZero"].Value = t.TriggerZeroAddress;
                    newRow.Cells["Done"].Value = t.ResultDoneAddress;
                    newRow.Cells["ZeroDone"].Value = t.ZeroDoneAddress;
                    newRow.Cells["Result"].Value = t.ResultAddress;
                }
            }
        }
        private string[] PortNames = SerialPort.GetPortNames();
        DataGridViewComboBoxColumn portNameSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn baudRateSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn paritySerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn dataBitSerialColumn = new DataGridViewComboBoxColumn();
        DataGridViewComboBoxColumn stopBitSerialColumn = new DataGridViewComboBoxColumn();
        private void InitGagfColumns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpIP", "IP");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TcpPort", "端口");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Trigger", "触发称重地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "TriggerZero", "触发清零地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Done", "称重完成地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "ZeroDone", "清零完成地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTcp, "Result", "称重结果地址");
            this.dataGridViewTcp.DoubleBufferedDataGirdView(true);
            this.dataGridViewTcp.InitStyle();
            CommonHelper.InitComboGridColumn(portNameSerialColumn, "PortName", "串口", PortNames);
            CommonHelper.InitComboGridColumn(baudRateSerialColumn, "BaudRate", "波特率", new string[] { "2400", "4800", "9600", "14400", "19200", "115200" });
            CommonHelper.InitComboGridColumn(paritySerialColumn, "Parity", "校验位", new string[] { "0", "1", "2", "3", "4" });
            CommonHelper.InitComboGridColumn(dataBitSerialColumn, "DataBit", "数据位", new string[] { "5", "6", "7", "8" });
            CommonHelper.InitComboGridColumn(stopBitSerialColumn, "StopBit", "停止位", new string[] { "0", "1", "2", "3" });
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Name", "名称");
            this.dataGridViewSerial.Columns.Add(portNameSerialColumn);
            this.dataGridViewSerial.Columns.Add(baudRateSerialColumn);
            this.dataGridViewSerial.Columns.Add(paritySerialColumn);
            this.dataGridViewSerial.Columns.Add(dataBitSerialColumn);
            this.dataGridViewSerial.Columns.Add(stopBitSerialColumn);
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Trigger", "触发称重地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Result", "称重结果地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "Done", "称重完成地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "TriggerZero", "触发清零地址");
            CommonHelper.CreateTextGridColumn(this.dataGridViewSerial, "ZeroDone", "清零完成地址");
            this.dataGridViewSerial.DoubleBufferedDataGirdView(true);
            this.dataGridViewSerial.InitStyle();
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "数据保存中，请稍候......");
            if (GlobalStatus.APP == EAppStatus.RUN)
            {
                HWMessageBox.Show(this, "设备运行中，不允许修改参数");
                CommonHelper.CloseWaiting();
                return;
            }
            try
            {
                bool isValidTcp = true, isValidSerial = true, isValidOther = true;
                int timeout = 200;
                List<GagfTcpParam> tcpList = new List<GagfTcpParam>();
                List<GagfComParam> comList = new List<GagfComParam>();
                if (this.dataGridViewTcp.Rows != null && this.dataGridViewTcp.Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataGridViewRow row in this.dataGridViewTcp.Rows)
                    {
                        var name = CommonHelper.GetCellStringValue(row, "Name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            if (tcpList.Find(v => v.Remark.Equals(name)) != null)
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                break;
                            }
                            var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                            var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                            var trigger = CommonHelper.GetCellStringValue(row, "Trigger");
                            var triggerZero = CommonHelper.GetCellStringValue(row, "TriggerZero");
                            var result = CommonHelper.GetCellStringValue(row, "Result");
                            var done = CommonHelper.GetCellStringValue(row, "Done");
                            var zeroDone = CommonHelper.GetCellStringValue(row, "ZeroDone");
                            IPAddress ipValue = null;
                            if (ip == null || !IPAddress.TryParse(ip, out ipValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的IP有误");
                                isValidTcp = false;
                                break;
                            }
                            int portValue = 9004;
                            if (port == null || !int.TryParse(port, out portValue))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的端口有误");
                                isValidTcp = false;
                                break;
                            }
                            if (string.IsNullOrWhiteSpace(trigger)
                                || string.IsNullOrWhiteSpace(result)
                                || string.IsNullOrWhiteSpace(done))
                            {
                                HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的地址有误");
                                isValidTcp = false;
                                break;
                            }
                            tcpList.Add(new GagfTcpParam()
                            {
                                Remark = name,
                                ServerIP = ipValue.ToString(),
                                ServerPort = portValue,
                                TriggerAddress = trigger,
                                TriggerZeroAddress = triggerZero == null ? "" : triggerZero,
                                ResultAddress = result,
                                ResultDoneAddress = done,
                                ZeroDoneAddress = zeroDone == null ? "" : zeroDone,
                            });
                        }
                        rowIndex++;
                    }
                }
                if (isValidTcp)
                {
                    if (this.dataGridViewSerial.Rows != null && this.dataGridViewSerial.Rows.Count > 0)
                    {
                        int rowIndex = 0;
                        foreach (DataGridViewRow row in this.dataGridViewSerial.Rows)
                        {
                            var name = CommonHelper.GetCellStringValue(row, "Name");
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                if (comList.Find(v => v.Remark.Equals(name)) != null)
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的名称有重复");
                                    break;
                                }
                                var portName = CommonHelper.GetCellStringValue(row, "PortName");
                                var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                                var parity = CommonHelper.GetCellStringValue(row, "Parity");
                                var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                                var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                                var trigger = CommonHelper.GetCellStringValue(row, "Trigger");
                                var triggerZero = CommonHelper.GetCellStringValue(row, "TriggerZero");
                                var result = CommonHelper.GetCellStringValue(row, "Result");
                                var done = CommonHelper.GetCellStringValue(row, "Done");
                                var zeroDone = CommonHelper.GetCellStringValue(row, "ZeroDone");
                                if (string.IsNullOrWhiteSpace(portName))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的串口有误");
                                    isValidSerial = false;
                                    break;
                                }
                                int baudRateValue = int.Parse(baudRate);
                                int parityValue = int.Parse(parity);
                                int dataBitValue = int.Parse(dataBit);
                                int stopBitValue = int.Parse(stopBit);
                                if (string.IsNullOrWhiteSpace(trigger)
                                || string.IsNullOrWhiteSpace(result)
                                || string.IsNullOrWhiteSpace(done))
                                {
                                    HWMessageBox.Show(this, $"第{(rowIndex + 1)}行的地址有误");
                                    isValidSerial = false;
                                    break;
                                }
                                comList.Add(new GagfComParam()
                                {
                                    Remark = name,
                                    BaudRate = baudRateValue,
                                    Parity = parityValue,
                                    DataBits = dataBitValue,
                                    PortName = portName,
                                    StopBits = stopBitValue,
                                    TriggerAddress = trigger,
                                    TriggerZeroAddress = triggerZero,
                                    ResultAddress = result,
                                    ResultDoneAddress = done,
                                    ZeroDoneAddress = zeroDone,
                                });
                            }
                            rowIndex++;
                        }
                    }
                }
                if (isValidTcp && isValidSerial)
                {
                    if (!int.TryParse(this.textBoxTimeout.Text, out timeout))
                    {
                        isValidOther = false;
                        HWMessageBox.Show(this, "超时时间有误");
                    }
                }
                if (isValidTcp && isValidSerial && isValidOther)
                {
                    GagfHelper.SaveAutoGagfTcpConfig(tcpList);
                    GagfHelper.SaveAutoGagfComConfig(comList);
                    var otherConfig = BusinessConfig.Instance();
                    otherConfig.GagfTimeout = timeout;
                    otherConfig.GagfIsQ = this.radioButtonQ.Checked;
                    otherConfig.GagfWeight2 = this.checkBoxConfirmRead.Checked;
                    otherConfig.GagfRezeroAck = this.checkBoxRezeroACK.Checked;
                    otherConfig.Save();
                    LogHelper.Info($"修改Gagf配置\r\n{CommonHelper.GetJsonString(otherConfig)}\r\n{CommonHelper.GetJsonString(tcpList)}\r\n{CommonHelper.GetJsonString(comList)}");
                    APPInstance.ResetHelpers();
                    this.DialogResult = DialogResult.OK;
                    HWMessageBox.Show(this, "保存成功");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
            }
            CommonHelper.CloseWaiting();
        }
        private void dataGridViewTcp_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
        }
        private void dataGridViewTcp_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
        }
        private void dataGridViewSerial_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(portNameSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(paritySerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(baudRateSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(dataBitSerialColumn))
                || e.ColumnIndex.Equals(this.dataGridViewSerial.Columns.IndexOf(stopBitSerialColumn)))
            {
                SendKeys.Send("{F4}");
            }
        }
        private void dataGridViewSerial_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            var portNameCell = e.Row.Cells["PortName"] as DataGridViewComboBoxCell;
            if (portNameCell != null && PortNames != null && PortNames.Length > 0)
            {
                portNameCell.Value = PortNames[0];
            }
            var baudRateCell = e.Row.Cells["BaudRate"] as DataGridViewComboBoxCell;
            if (baudRateCell != null)
            {
                baudRateCell.Value = "9600";
            }
            var parityCell = e.Row.Cells["Parity"] as DataGridViewComboBoxCell;
            if (parityCell != null)
            {
                parityCell.Value = "0";
            }
            var stopBitCell = e.Row.Cells["StopBit"] as DataGridViewComboBoxCell;
            if (stopBitCell != null)
            {
                stopBitCell.Value = "1";
            }
            var dataBitCell = e.Row.Cells["DataBit"] as DataGridViewComboBoxCell;
            if (dataBitCell != null)
            {
                dataBitCell.Value = "8";
            }
        }
        private void toolStripMenuItemRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewTcp.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewTcp.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var ip = CommonHelper.GetCellStringValue(row, "TcpIP");
                    var port = CommonHelper.GetCellStringValue(row, "TcpPort");
                    IPAddress ipValue = null;
                    if (ip == null || !IPAddress.TryParse(ip, out ipValue))
                    {
                        HWMessageBox.Show(this, $"IP有误");
                    }
                    else
                    {
                        int portValue = 502;
                        if (!int.TryParse(port, out portValue))
                        {
                            HWMessageBox.Show(this, $"端口有误");
                        }
                        else
                        {
                            var helper = APPInstance.HELPERS != null ?
                                APPInstance.HELPERS.Find(v => v is GagfHelper && v.Name.Equals(name.ToString())
                                && v.CommunicationType == ECommunicationType.TCP && v.IsConnected) : null;
                            if (helper != null)
                            {
                                try
                                {
                                    string content = CommonHelper.RemoveEnterString((helper as GagfHelper).GetWeight());
                                    HWMessageBox.Show(this, $"结果：{content}");
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                            }
                            else
                            {
                                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                try
                                {
                                    socket.ReceiveTimeout = 1000;
                                    socket.ConnectAsync(ipValue, portValue).Wait(500);
                                    if (socket.Connected)
                                    {
                                        socket.Send(mReadWeightCommand);
                                        byte[] buffer = new byte[1024];
                                        int length = socket.Receive(buffer);
                                        if (length > 0)
                                        {
                                            string content = Encoding.UTF8.GetString(buffer.Take(length).ToArray());
                                            HWMessageBox.Show(this, $"结果：{content}");
                                        }
                                        else
                                        {
                                            HWMessageBox.Show(this, "通讯异常");
                                        }
                                    }
                                    else
                                    {
                                        HWMessageBox.Show(this, "无法建立连接");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                                }
                                finally
                                {
                                    if (socket != null && socket.Connected)
                                    {
                                        socket.Close();
                                        socket = null;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }
        private void toolStripMenuItemSerialRead_Click(object sender, EventArgs e)
        {
            CommonHelper.ShowWaiting(this, "功能触发中，请稍候......");
            var cells = this.dataGridViewSerial.SelectedCells;
            if (cells != null && cells.Count > 0)
            {
                var row = this.dataGridViewSerial.Rows[cells[0].RowIndex];
                var name = CommonHelper.GetCellStringValue(row, "Name");
                if (!string.IsNullOrWhiteSpace(name))
                {
                    var portName = CommonHelper.GetCellStringValue(row, "PortName");
                    var baudRate = CommonHelper.GetCellStringValue(row, "BaudRate");
                    var parity = CommonHelper.GetCellStringValue(row, "Parity");
                    var dataBit = CommonHelper.GetCellStringValue(row, "DataBit");
                    var stopBit = CommonHelper.GetCellStringValue(row, "StopBit");
                    if (string.IsNullOrWhiteSpace(portName))
                    {
                        HWMessageBox.Show(this, $"串口有误");
                    }
                    else
                    {
                        int baudRateValue = int.Parse(baudRate);
                        int parityValue = int.Parse(parity);
                        int dataBitValue = int.Parse(dataBit);
                        int stopBitValue = int.Parse(stopBit);
                        var helper = APPInstance.HELPERS != null ?
                            APPInstance.HELPERS.Find(v => v is GagfHelper
                            && v.Name.Equals(name)
                            && v.CommunicationType == ECommunicationType.SERIAL
                            && v.IsConnected) : null;
                        if (helper != null)
                        {
                            try
                            {
                                string content = CommonHelper.RemoveEnterString((helper as GagfHelper).GetWeight());
                                HWMessageBox.Show(this, $"结果：{content}");
                            }
                            catch (Exception ex)
                            {
                                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                            }
                        }
                        else
                        {
                            SerialPort serialPort = new SerialPort(portName, baudRateValue,
                            CommonHelper.GetEnumByRealValue(parityValue, Parity.None), dataBitValue,
                            CommonHelper.GetEnumByRealValue(stopBitValue, StopBits.One));
                            try
                            {
                                serialPort.Open();
                                serialPort.Write(mReadWeightCommand, 0, mReadWeightCommand.Length);
                                int length = 0;
                                for (var i = 0; i < 3; i++)
                                {
                                    System.Threading.Thread.Sleep(1);
                                    length = serialPort.BytesToRead;
                                    if (length > 0)
                                    {
                                        break;
                                    }
                                    System.Threading.Thread.Sleep(1000);
                                }
                                if (length > 0)
                                {
                                    byte[] buffer = new byte[length];
                                    serialPort.Read(buffer, 0, length);
                                    string content = Encoding.UTF8.GetString(buffer);
                                    HWMessageBox.Show(this, $"结果：{content}");
                                }
                                else
                                {
                                    HWMessageBox.Show(this, "通讯异常");
                                }
                            }
                            catch (Exception ex)
                            {
                                HWMessageBox.Show(this, $"发生异常：{ex.Message}");
                            }
                            finally
                            {
                                if (serialPort != null && serialPort.IsOpen)
                                {
                                    serialPort.Close();
                                    serialPort = null;
                                }
                            }
                        }
                    }
                }
                else
                {
                    HWMessageBox.Show(this, "名称有误");
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录");
            }
            CommonHelper.CloseWaiting();
        }
        private void buttonMaxSize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }
        private void FormGagf_Shown(object sender, EventArgs e)
        {
        }
        private void FormGagf_FormClosing(object sender, FormClosingEventArgs e)
        {            
        }
    }
}
